package ru.spb.osll.myfit.wikiverifier.suggester;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Vector;

import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableCell;
import ru.spb.osll.myfit.wikiverifier.distance.MyFitDistance;

public class DoFixtureSuggester implements TemplateSuggester {

	@Override
	public double distance(Table table, Table template) {
		LinkedList<String> tableLines = new LinkedList<String>();
		for (Vector<TableCell> line : table.getData()) {
			tableLines.add(oneLineTableMethod(line));
		}
		
		LinkedList<String> templateLines = new LinkedList<String>();
		for (Vector<TableCell> line : template.getData()) {
			templateLines.add(oneLineTableMethod(line));
		}

		double distance = 0;
		Iterator<String> tableIter = tableLines.iterator();
		Iterator<String> templateIter = templateLines.iterator();
		StringBuffer tableStr = new StringBuffer();
		StringBuffer templateStr = new StringBuffer();


		while (tableIter.hasNext() && templateIter.hasNext()) {
			tableStr.append(tableIter.next());
			tableStr.append(" ");
			templateStr.append(templateIter.next());
			templateStr.append(" ");
		}
		
		while (tableIter.hasNext() ) {
			tableStr.append(tableIter.next());
			tableStr.append(" ");
		}
		
		distance = MyFitDistance.calc(tableStr.toString(), templateStr.toString());
		
		return distance;
	}

	@Override
	public Table getSuggestion(Table table, Table template) {
		Table templateWithValues = new Table(template.getStyle());
		Iterator<Vector<TableCell>> tableIter = table.getData().iterator();
		Iterator<Vector<TableCell>> templateIter = template.getData().iterator();

		while (tableIter.hasNext() && templateIter.hasNext()) {
			Vector<TableCell> tableLine = tableIter.next();
			Vector<TableCell> templateLine = templateIter.next();
			if (tableLine.size() == templateLine.size()) {
				templateWithValues.addLine(templateLineWithValues(tableLine,
						templateLine));
			} else {
				templateWithValues.addLine(templateLine);
			}
		}
		while (templateIter.hasNext()) {
			Vector<TableCell> templateLine = templateIter.next();
			templateWithValues.addLine(templateLine);
		}
		
		return templateWithValues;
	}
	
	private String oneLineTableMethod(Vector<TableCell> line) {
		String res = "";

		int length = (line.size() % 2 == 0) ? line.size() - 1: line.size();

		for (int i = 0; i < length; i += 2) {
			res = res + line.get(i).getText();
		}

		return res;
	}
	
	private Vector<TableCell> templateLineWithValues(Vector<TableCell> tableLine,
			Vector<TableCell> templateLine) {
		Vector<TableCell> resLine = new Vector<TableCell>();
		for (int i = 0; i < tableLine.size(); i++) {
			if (i % 2 == 0) {
				resLine.add(new TableCell(templateLine.get(i).getText()));
			} else {
				resLine.add(new TableCell(tableLine.get(i).getText()));
			}
		}

		return resLine;
	}
}
